﻿using Ordering.Domain.Events;
using Ordering.Domain.SeedWork;

namespace Ordering.Domain.Aggregate
{
    public class Order : Entity, IAggregateRoot
    {
        public override string Id { get; }

        public decimal TotalAmount { get; private set; }

        public string BuyerId { get; private set; }

        public OrderStatus Status { get; private set; }

        public DateTime CreationTime { get; private set; } = DateTime.Now;

        private readonly List<OrderItem> _items = new List<OrderItem>();

        public IReadOnlyCollection<OrderItem> List => _items;

        protected Order()
        {

        }

        public Order( decimal totalAmount, string buyerId)
        {
            TotalAmount = totalAmount;
            Status = OrderStatus.待支付;
            BuyerId = buyerId;
            AddDomainEvent(new CreateOrderDomainEvent(this));
        }


        public void AddOrderItme(OrderItem item)
        {
            TotalAmount = item.SalesPrice + item.GoodsNumber;
            _items.Add(item);
        }

        public void ClearOrderItme(OrderItem item)
        {
            _items.Clear();
        }

        public void Paymeny()
        {
            if (Status != OrderStatus.待支付)
            {
                throw new DomainException("只有待支付的订单才能支付");
            }
            Status = OrderStatus.待发货;
            AddDomainEvent(new PaymentOrderDomainEvent(this));
        }

        public void Deliver()
        {
            if (Status != OrderStatus.待发货)
            {
                throw new DomainException("只有待发货的订单才能发货");
            }
            Status = OrderStatus.待确认;
        }
    }
}
